﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using LX.Web.Excel;

namespace LX.Web.Excel
{
    public  class ExportObject : IExport
    {
        /// <summary>
        /// 鉴别是否达标
        /// </summary>
        /// <param name="propertyname"></param>
        /// <returns></returns>
        public virtual bool? Discriminate(string propertyname)
        {
            return null;
        }


        public List<ExcelCell> GetExcelRow()
        {
            List<ExcelCell> result = new List<ExcelCell>();
            var ps = this.GetType().GetProperties();

            foreach (var p in ps)
            {
                var exportattrs = p.GetCustomAttributes(typeof(ExportAttribute), true);
                if (exportattrs != null && exportattrs.Any())
                {
                    ExportAttribute attr = (ExportAttribute)exportattrs[0];
                    ExcelCell cell = new ExcelCell();
                    //cell.Col = attr.Col;
                    cell.MergeVertical = attr.MergeVertical;
                    cell.Name = (attr.Name == null ? p.Name : attr.Name);
                    object value = p.GetValue(this, null);
                    if (value != null)
                    {
                        if (value.GetType() == typeof (decimal))
                        {
                            value = ((decimal) value).toInt(attr.Precision);
                        }
                        if (!String.IsNullOrWhiteSpace(attr.Format))
                        {
                            value = string.Format(attr.Format, value);
                        }
                        cell.Value = value.ToString();
                    }
                    else
                    {
                        cell.Value = "";
                    }
                    cell.Colspan = attr.Colspan;
                    cell.BackBround = attr.BackBround;
                    var discriminateresult = this.Discriminate(p.Name);
                    if (discriminateresult!=null)
                    {
                        if (discriminateresult.Value)
                        {
                            cell.BackBround = ExcelCellBg.Pass;
                        }
                        else
                        {
                            cell.BackBround = ExcelCellBg.Warning;
                        }
                    }
                    result.Add(cell);
                }
            }
            return result;
        }
    }


}
